package com.ypz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ypz.reggie.common.R;
import com.ypz.reggie.entity.Category;
import com.ypz.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 分类管理
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 保存菜品或套餐
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {

        categoryService.save(category);

        return R.success("保存成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);

        Page<Category> page1 = categoryService.page(categoryPage, lqw);

        return R.success(page1);
    }

    /**
     * 删除没有关联的分类
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(Long id) {

        boolean b = categoryService.deleteByIds(id);

        if (b) {
            return R.success("删除成功");
        }
        return R.error("删除失败");

    }

    /**
     * 更新分类
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {

        categoryService.updateById(category);
        return R.success("更新成功");

    }

    /**
     * 查询分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        Integer type = category.getType();
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();

        //查询条件
        lqw.eq(type != null,Category::getType, type);
        //排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> categoryList = categoryService.list(lqw);

        return R.success(categoryList);
    }

}
